package com.dh.leetcode.three;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;

/**
 * @ClassName: _349_IntersectionOfTwoArrays
 * @Description: 两个数组的交集
 * <p>
 * 给定两个数组，编写一个函数来计算它们的交集。
 * <p>
 * https://leetcode-cn.com/problems/intersection-of-two-arrays/
 * <p>
 * 示例 1：
 * 输入：nums1 = [1,2,2,1], nums2 = [2,2]
 * 输出：[2]
 * @Author: shouzimu
 * @Date: 2020/11/13 16:34
 */
public class _349_IntersectionOfTwoArrays {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (null == nums1 || null == nums2) {
            return new int[0];
        }
        int len = nums1.length > nums2.length ? nums2.length : nums1.length;
        int[] res = new int[len];
        len = 0;
        for (int n1 : nums1) {
            for (int n2 : nums2) {
                if (n1 == n2) {
                    boolean exist = false;
                    for (int j = 0; j < len; j++) {
                        if (res[j] == n1) {
                            exist = true;
                            break;
                        }
                    }
                    if (!exist) {
                        res[len++] = n2;
                    }
                }
            }
        }
        int[] newRes = new int[len];
        System.arraycopy(res, 0, newRes, 0, len);
        return newRes;
    }

    @Test
    public void intersectionTest() {
        int[] nums1 = new int[]{4, 9, 5};
        int[] nums2 = new int[]{9, 4, 9, 8, 4};

        int[] res = intersection(nums1, nums2);
        Arrays.sort(res);
        int[] expect = new int[]{9, 4};
        Arrays.sort(expect);
        Assert.assertArrayEquals(res, expect);
    }
}
